<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .active {
      background-color: #999;
    }
  </style>
</head>
<body>
  <div id="app">
    <!-- 跨域：域名、协议、端口号必须全部一致，否则就是跨域。这是浏览器的同源策略 -->
    <!-- jsonp：动态增加script标签，解决跨域问题。原理：script、link、img地址可以跨域 -->
    <h1>我的百度</h1>
    <input
      type="text"
      v-model="word"
      @keyup.down="down"
      @keyup.up="up"
      @keyup.enter="open"
    >
    <p v-for="(item, index) in list" :key="index" :class="{active:index===num}">
      {{item}}
    </p>
  </div>
  <script src="../vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        word: '',
        // 结果列表
        list: [],
        // 当前选择第几项
        num: 0
      },
      watch: {
        word(val) {
          // console.log(val);
          // 创建script标签
          let script = document.createElement('script');
          // 准备src属性
          // cb是jsonp的回调
          script.src = 'http://suggestion.baidu.com/su?cb=cb&wd='+val;
          // 插入到body中
          document.body.append(script);
        }
      },
      methods: {
        down() {
          this.num<4 ? this.num ++ : this.num=0
        },
        up() {
          this.num>0 ? this.num -- : this.num=4
        },
        open() {
          // 跳转页面
          console.log(this.list[this.num]);
          window.open('http://www.baidu.com/s?wd='+this.list[this.num])
        }
      },
    })
    function cb(res) {
      vm.list = res.s.filter((item,index) => {
        // 只取前五条
        return index < 5
      });
    }
  </script>
</body>
</html>